Free Web Development Online Tutorials, Learn to Code
Asp.net web api security interview questions, job interview questions and answers software jobs

Web API Interview Questions in Asp.net

C# web service interview questions

Asp.net Web API security interview questions

What is the default MediaTypeFormatter in asp.net Web API?
default MediaTypeFormatter is XML
What are the different MediaTypeFormatter in Web API?
There are XmlFormatter, JsonFormatter, FormUrlEncodedFormatter, we can create any custom MediaTypeFormatter using custom class inherited from same base MediaTypeFormatter class.
How to send action message back from Web API to client
We should create HttpResponseMessage type post instead of void, then we can create a response object to send back to client.
var returnMessage = Request.CreateResponse(HttpStatusCode.Created, c);
How to send error message back from Web API to client

We should create HttpResponseMessage type post instead of void, then we can create a response object with exception object, we can write try catch block this way.

try                
{

}
catch (Exception ex)
{
    var returnErrMessage = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);

    return returnErrMessage;
}
How to return only JSON or XML type from a Web API project?

Well, we can fix the (Formatters) return type, we can remove any formatter (MediaTypeFormatter) from web API project just by adding few lines in “WebApiConfig.cs”

In following example suppose we want to return only JSON type,
So added config.Formatters.Remove(config.Formatters.XmlFormatter);

public static class WebApiConfig                
{
    public static void Register(HttpConfiguration config)
    {
            config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional });
                
        //Suppose we want to return only JSON type,then we can remove XML formatter this way.
        config.Formatters.Remove(config.Formatters.XmlFormatter);                
    }
}
Comment
Name
Email
Website
Subscribe