I want create ASP.NET WEB API with swagger documentation, but I have strange problem. When I set api format using my own implemenation of JSON formatter, swagger documenation is disabled. In console I can see that JavaScript Exception is throwing.
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var jsonFormatter = new JsonMediaTypeFormatter();
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
{"swagger":"2.0","info":{"version":"v1","title":"REST","description":null,"termsOfService":null,"contact":null,"license":null,"vendorExtensions":{}},"host":"localhost:58144","basePath":null,"schemes":["http"],"consumes":null,"produces":null,"paths":{"/api/Users":{"$ref":null,"get":{"tags":["Users"],"summary":null,"description":null,"externalDocs":null,"operationId":"Users_GetUsers","consumes":[],"produces":["application/json","text/json","application/xml","text/xml"],"parameters":null,"responses":{"200":{"description":"OK","schema":{"$ref":null,"format":null,"title":null,"description":null,"default":null,"multipleOf":null,"maximum":null,"exclusiveMaximum":null,"minimum":null,"exclusiveMinimum":null,"maxLength":null,"minLength":null,"pattern":null,"maxItems":null,"minItems":null,"uniqueItems":null,"maxProperties":null,"minProperties":null,"required":null,"enum":null,"type":"array","items":
Related
I am trying to enable cors in my ASP.NET Web API. I am using WebApiConfig.cs (not attributes in controller) to keep configuration for origins in my Web.config file. WebApiConfig.cs looks like this:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
//CORS settings
string allowedOrigins = ConfigurationManager.AppSettings["AllowedOrigins"].ToString();
var cors = new EnableCorsAttribute(allowedOrigins, "*", "*");
config.EnableCors(cors);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
3rd parameter of EnableCorsAttribute() constructor is a "Comma-separated list of methods that are supported by the resource."
I have a controller with public methods but I want to allow only certain methods to be available from another domain.
I tried to list them by name:
var cors = new EnableCorsAttribute(allowedOrigins, "*", "SaveChatResult,MapSessionToInteraction");
I tried to list them by [Route] attribute:
var cors = new EnableCorsAttribute(allowedOrigins, "*", "api/Widget/SaveChatResult,api/Widget/MapSessionToInteraction");
But only "*" works for all. I can not control it by methods. How to put this 3rd string method parameter to enable cors only for desired methods in controller?
I'm using attribute routing in a Web API controller (.NET Framework 4.5.2 - don't ask, I'm trying to get approval for time to move everything forward).
I have applied a [RoutePrefix] attribute to my ApiController.
I have two controller actions, both HttpGets. Each has a [Route] attribute applied.
I'm using Swagger to auto-generate docs. In the docs for this controller I see three endpoints listed - two for my controller actions, and another HttpGet with the bare controller route.
That is what I have is this:
[RoutePrefix("api/test/Tickets")]
public class TestTicketsController : ApiController
{
[HttpGet, Route("")]
public HttpResponseMessage GetTickets()
{
....
}
[HttpGet, Route("since")]
public HttpResponseMessage GetTicketsSince(string since)
{
....
}
}
And In the generated Swagger docs I see three endpoints:
GET api/test/Tickets
GET api/test/Tickets/since
GET api/TestTickets
This third endpoint, api/TestTickets, seems to be derived from the class name of the controller, ignored my routing attributes. And when I call it, I get an HTTP 200 with an empty body, despite not having defined an action for it.
Where is this coming from? And how can I stop it from being generated?
===
It was suggested that I remove the [HttpGet, Route("")] attribute. If I do, I get an error:
Multiple operations with path 'api/TestTickets' and method 'GET'.
It was also suggested that I include my WebApiConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "swagger_root",
routeTemplate: "",
defaults: null,
constraints: null,
handler: new RedirectHandler((message => message.RequestUri.ToString()), "api/docs/index"));
var mediaType = new MediaTypeHeaderValue("application/json");
var formatter = new JsonMediaTypeFormatter();
formatter.SupportedMediaTypes.Clear();
formatter.SupportedMediaTypes.Add(mediaType);
config.Formatters.Clear();
config.Formatters.Add(formatter);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
If I comment-out the config.Routes.MapHttpRoute, the extra endpoint goes away.
Now it's just a matter of determining whether we have any controllers that expect this default endpoint to be there.
Thanks.
abdulg pointed out in a comment, rather than in an answer - default routes are configured in WebApiConfig.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
I have an ASP.NET web api that was created with Entity framework.I added my controller in the controller's folder and it generated the API code for me.but when i run the application it does not show the controller that i added,it only shows the default API page that comes with the application like below.
This is what it displays
I would like it to look like this
Expected Output
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
NOTE: Add 'ActionApi' route in WebApiConfig.cs file
Every time I make a POST request with Fiddler, an UnsupportedMediaTypeException is raised. Am I missing something?
The Controller:
[Route("api/contacts")]
public IHttpActionResult Post([FromBody]ContactDTO contact)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
//Other operations
return Created(contact);
}
WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(
new MediaTypeHeaderValue("application/json"));
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
Fiddler request
After looking a bit further into my code, I noticed something. My controller class was inheriting from ODataController. I just changed the inheritance to ApiController and everything works fine now.
I literally followed this tutorial,
http://jerther.blogspot.com/2014/11/aspnet-web-api-2-help-pages-odata_28.html
Excepting the return format as JSON but not sure how am getting back BSON, am new to BSON never heard about.
OData, WebAPI, EF (repository pattern)is what am using. Any suggestions on how to get back JSON instead of BSON.
Here is my Code, what i did so far
WebApiConfig:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
// config.SuppressDefaultHostAuthentication();
// config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
// Remove the XML formatter
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.Formatters.Add(new JsonMediaTypeFormatter());
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/v1/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
ODataConfig.cs - used it in the routeConfig.cs
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes(); //This has to be called before the following OData mapping, so also before WebApi mapping
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Item>("Item");
config.MapODataServiceRoute("ODataRoute", "api", builder.GetEdmModel());
}
RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Controller.
[EnableQuery]
[ODataRoute]
public IQueryable<Item> GetItem()
{
var result = _cRepository.GetAll();
return result.AsQueryable();
}
My Controller was referencing to System.Web.Http.OData, uninstalled all the nuget packages related to Odata,WebAPI and reinstalled. Referenced Controller to System.Web.OData and everything looks good now returns JSON. Thanks a lot for all your responses.