I have an ASP.NET Core v2.1 project with Swashbuckle.AspNetCore package.
My code is:
/// <summary>
/// Set new android token for the current driver
/// </summary>
/// <remarks>
/// Sample request:
///
/// PUT /SetToken?token=new_token
///
/// </remarks>
/// <param name="token">can't be null or empty</param>
/// <returns></returns>
/// <response code="204">If executed successfully</response>
/// <response code="400">if token is null or empty</response>
/// <response code="404">if user is not a driver; if driver is not found (removed etc); if user does not have a profile</response>
[ProducesResponseType(204)]
[ProducesResponseType(400)]
[ProducesResponseType(404)]
[HttpPut]
[Route("SetToken")]
[UserIsNotDriverException]
[NullReferenceException]
[DriverWithoutProfileException]
public async Task<IActionResult> SetToken([FromQuery]string token)
{
I want to mark query parameter as required. How can I do it? Pay attention, I pass parameter in query string, not inside body etc
You can add the BindRequired attribute to your parameter.
public async Task<IActionResult> SetToken([FromQuery, BindRequired]string token)
You can do it like this.
public async Task<IActionResult> SetToken([FromQuery, SwaggerParameter("Token Description", Required = True)]string token)
Using this library Swashbuckle.AspNetCore.Annotations will help.
Related
I have a web api in asp.net-core and I wanted to know how to put paragraphs as descriptions on the end points? I tried \n \n , nothing works. I am putting the description in the "remarks" xml.
Thanks
First, you must configure Swashbuckle to use the documentation XML.
Then, use <summary> and <remarks> tags for operation summary and description.
/// <summary>
/// Summary for ActionWithSummaryAndRemarksTags
/// </summary>
/// <remarks>
/// Remarks for ActionWithSummaryAndRemarksTags
/// </remarks>
public ActionResult ActionWithSummaryAndRemarksTags()
You can use Markdown to construct more complex documents:
/// <summary>
/// This is a short summary
/// </summary>
/// <remarks>
/// ## Usage
/// ...
/// ```
/// <![CDATA[
/// {
/// "html": "<h1>escape HTML with CDATA blocks</h1><img src=\"https://unsplash.it/400/200\" />"
/// }
/// ]]>
/// ```
///
/// ### A title
/// A paragrapth with [a link](https://example.com).
///
/// ```html
/// <h1>hello world, this is a code block</h1>
/// <img src="data:image/jpg,base64;..." />
/// ```
/// This is an inline code `https://unsplash.it/200/100`.
///
/// This is a separate paragraph
/// </remarks>
I have the following application service method.
public class MyAppService : AsyncCrudAppService<Entity, Dto, Guid, GetAllRequest, CreateRequest, UpdateRequest, GetRequest, DeleteRequest>, IMyAppService
{
/// <summary>
/// Return cities associated with zip code
/// </summary>
/// <param name="zipCode">Zip code to search. If null all cities are returned.</param>
/// <returns>Cities associated with zip code.</returns>
/// <exception cref="EntityNotFoundException">If zip code is provided but no associated city is found</exception>
/// <response code="404">If no city with zip code found</response>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<GetCitiesByZipCodeResponse> GetCitiesByZipCode(int? zipCode = null)
{
...
}
}
Even though I have a summary describing what the endpoint does, it is not displayed in swagger. What is the right way to add rich information to Swagger about app service methods?
It did pick up the effect of ProducesResponseType(StatusCodes.Status404NotFound) and showing 404 as possible response though.
Swagger for GetCitiesByZipCode
AppServices are automatically converted to Controllers. But your custom Swagger attributes are stripped off. If you have a such requirement, then create a new MyContoller and call your AppService methods inside the Controller. And disable remote service function for your Appservice with the following attribute
[RemoteService(IsEnabled = false)]
https://docs.abp.io/en/abp/latest/API/Auto-API-Controllers#remoteservice-attribute
I was using ASP.NET4.5 and visual studio 2013 to create a sample application Wingtip Toys. But when trying to display data item and details It showing error in the last line of code bellow which is-
protected global::System.Web.UI.WebControls.ListView ProductList;
ProductList: member names cannot be the same at their enclosing type.
namespace WingtipToys
{
public partial class ProductList
{
/// <summary>
/// ProductList control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ListView ProductList;
}
}
The class ProductList cannot contain a field, property, or method named ProductList as well. Try using the following code instead:
public partial class ProductList
{
/// <summary>
/// ProductList control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ListView Products;
}
Likewise, a namespace cannot contain a class with the same name as the namespace.
I am using the WebApi Help pages within an MVC4 project.
As per the following link, http://blogs.msdn.com/b/yaohuang1/archive/2012/10/13/asp-net-web-api-help-page-part-2-providing-custom-samples-on-the-help-page.aspx I have been setting the HelpPageConfig to set actual response types.
I have a controller that has two get methods on it
/// <summary>
/// Get the list of plans for a specified portfolio
/// </summary>
/// <param name="portfolioIdentifier">Portfolio Identifier (guid)</param>
/// <returns>
/// Returns a list of <see cref="RestDTOs.Plan"/> Plan objects
/// </returns>
public HttpResponseMessage Get(Guid portfolioIdentifier)
{
}
/// <summary>
/// Get full plan details.
/// </summary>
/// <param name="planIdentifier">Plan Identifier (guid)</param>
/// <returns>
/// Returns the <see cref="RestDTOs.Plan"/> Plan object
/// </returns>
[HttpGet]
public HttpResponseMessage Detail(Guid planIdentifier)
{
}
Within HelpPageConfig.cs i have added the following to try and set an example ResponseBody format
config.SetActualResponseType(typeof(Plan), "Plan", "GET");
This is working great on the Get method, but is not producing anything on the Detail method
What do I need to add to the HelpPageConfig so that the web api help will pick up and produce samples for the Detail method
MVC 5 has a built in attribute to set the response type.
More information here:
http://thesoftwaredudeblog.wordpress.com/2014/01/05/webapi-2-helppage-using-responsetype-attribute-instead-of-setactualresponsetype/
Just use:
ResponseType(typeof([Your_Class]))]
Try config.SetActualResponseType(typeof(Plan), "Plan", "Detail");...the second parameter here is expecting an action name...I see you are using Web API 1, so just FYI...in Web API 2, there is an attribute called ResponseType which you can use to decorate on an action to describe the actual response type for a given action..
I have two questions related to WCF Data Service:
is there a way to restrict the entities visible to a user according to her privileges ? For instance user in role super-user should be able to query the full 'Contact' entity but user with less privileges would only be able to see specific properties of the 'Contact' entity.
whenever a user runs a query on the service, I would like this to be logged in a database for audit purpose. Is this possible ?
1) There is the concept of interceptors: http://msdn.microsoft.com/en-us/library/dd744842.aspx
But I think they won't satisfy you in your case:
With change interceptors you can handle requests which try to change a specific entity. This could help you to avoid users without certain privileges to add/change/delete contact entities. With QueryInterceptors you can handle GET-Requests. But they don't allow you to restrict certain properties of your contact entity.
You are not the first with such requirements -> WCF Dataservice - modify object before returning results?
Maybe you could use a combination of a (custom) ServiceOperation and a View to handle this.
2) Yes, you can do this for instance by handling the ProcessingRequest-Event:
public class YourService : DataService<Entities>
{
/// <summary>
/// The logger.
/// </summary>
private readonly LogWriter logger;
/// <summary>
/// Initializes a new instance of the <see cref="YourService"/> class.
/// </summary>
public YourService()
{
this.logger = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
this.ProcessingPipeline.ProcessingRequest += this.ProcessingPipelineProcessingRequest;
}
/// <summary>
/// OnProcessingRequest
/// </summary>
/// <param name="sender">source</param>
/// <param name="e">event args</param>
public void ProcessingPipelineProcessingRequest(object sender, DataServiceProcessingPipelineEventArgs e)
{
this.logger.Write(new LogEntry { Message = "SOP ProcessingPipelineProcessingRequest: Unauthorized Access", Severity = TraceEventType.Warning })
}
}
You can find all those ProcessingPipeline-Events here: http://msdn.microsoft.com/en-us/library/system.data.services.dataserviceprocessingpipeline(v=vs.103).aspx