user1186065
user1186065

Reputation: 1877

how to use built-in content type negotiation and just get access to the decision

I wanted to take advantage of built-in content negotiator and just get access to decision what formatter is going to be used. I don't want to use Request.Headers.Accept and check for whether it is json or xml content type because there lot of things are involved in that decision. Is there a way I can check at controller level or override any class that tells me what formatter going to be used OR what request content type is?

thanks in advance.

Upvotes: 3

Views: 617

Answers (3)

Aliostad
Aliostad

Reputation: 81700

Tugberk has a blog on this. Have a look.

Upvotes: 0

Filip W
Filip W

Reputation: 27187

You can run conneg manually:

var conneg = Configuration.Services.GetContentNegotiator();
        var connegResult = conneg.Negotiate(
            typeof(YOUR_TYPE), Request, Configuration.Formatters
        );

And use the output whichever way you want:

//the valid media type
var mediaType = connegResult.MediaType;
//do stuff

//the relevant formatter
var formatter = connegResult.Formatter;
//do stuff

Upvotes: 2

Darrel Miller
Darrel Miller

Reputation: 142242

If you want to see what is going on then install a TraceWriter and you will see what the conneg does.

A TraceWriter looks something like:

    public class TraceWriter : ITraceWriter {
        public bool IsEnabled(string category, TraceLevel level) {
            return true;
        }

        public void Trace(HttpRequestMessage request, string category, TraceLevel level, Action<TraceRecord> traceAction) {
            var rec = new TraceRecord(request, category, level);
            traceAction(rec);
            Log(rec);
        }

        private void Log(TraceRecord record) {
            Console.WriteLine(record.Message);
        }
    }

and is installed like this,

     config.Services.Replace(typeof(ITraceWriter), new TraceWriter());

If you want to manually invoke conneg then you can use,

     config.Services.GetContentNegotiator().Negotiate(...)

Upvotes: 0

Related Questions