asp.net-web-api2

How to access a child object using OData, WebAPI and a DTO?

若如初见. 提交于 2019-12-04 21:52:49
From a WebAPI controller, I am returning a list of ProjectEditorDTO objects from an OData request /odata/ProjectEditor?$format=json&$inlinecount=allpages&$top=10 : [Queryable] public virtual IHttpActionResult Get(ODataQueryOptions<Website> odataQueryOptions) { var userId = UserContext.Identity.UserId; try { var results = odataQueryOptions.ApplyTo(_uow.Repository<Website>() .Query() .Get() .Where(u => u.UserId == userId) .OrderBy(o => o.WebsiteName)).Cast<Website>() .Select(s => new ProjectEditorDTO() { // projection WebsiteId = s.WebsiteId, WebsiteGUID = s.WebsiteGUID, WebsiteName = s

Post json data in body to web api

纵饮孤独 提交于 2019-12-04 21:17:52
问题 I get always null value from body why ? I have no problem with using fiddler but postman is fail. I have a web api like that: [Route("api/account/GetToken/")] [System.Web.Http.HttpPost] public HttpResponseBody GetToken([FromBody] string value) { string result = value; } My postman data: and header: 回答1: WebAPI is working as expected because you're telling it that you're sending this json object: { "username":"admin", "password":"admin" } Then you're asking it to deserialize it as a string

Response for preflight has invalid HTTP status code 404 - Angular 4 and Web API 2

被刻印的时光 ゝ 提交于 2019-12-04 21:04:58
In the service I am calling Web API(2)(hosted on different server than the front end angular 4 application) action method in order to retrieve some info. The action method needs authorization which I am doing using access token that I receive after logging into the application. Now, the code works fine in Microsoft edge, however gives me preflight error in chrome which I guess is CORS issue. Not sure how to resolve this. Can someone help me with this? Here is my code; getCompanyInfo(id: string) { let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',

OAuth access and refresh token control / management on user password change

◇◆丶佛笑我妖孽 提交于 2019-12-04 20:09:58
We are in the process of developing a in house mobile application and web api. We are using asp.net web api 2 with asp.net Identy 2 OAuth. I have got the api up and running and giving me a bearer token. However I want to slightly modify the process flow to something like along the lines of this: App user logs in to api with username and password. App receives Refresh-token which is valid for 30 days. App then requests an access token providing the api with the refresh token. ( Here I want to be able to invalidate a request if the user has changed their password or their account has been locked

how to solve “HTTP Error 500.19 - Internal Server Error” “<remove name=”ExtensionlessUrlHandler-Integrated-4.0“ />”

二次信任 提交于 2019-12-04 19:25:45
问题 i want to upload my webapi to iis but i am getting the following error Config Source: 24: </modules> 25: <handlers> 26: <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> here is my webconfig file <handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <remove name="OPTIONSVerbHandler" /> <remove name="TRACEVerbHandler" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode

IFormFile is always null when receiving file from console app

假如想象 提交于 2019-12-04 18:42:14
I have my WebApi method ready to accept file as parameter shown below: (e.g. uri " https://localhost:44397/api/uploadfile " [Route("api/[controller]")] [ApiController] public class UploadFileController : ControllerBase { [HttpPost] public async Task<IActionResult> Post([FromForm] IFormFile file) { } } Am using console app to send file to this api method, below is my code: public static void Send(string fileName) { using (var client = new HttpClient()) using (var content = new MultipartFormDataContent()) { client.BaseAddress = new Uri("https://localhost:44397"); var fs = new FileStream(fileName

How to create a “sub-resource” using OData without creating a collection property for it?

你说的曾经没有我的故事 提交于 2019-12-04 18:03:35
I'm creating a Web API 2 using OData v4 to provide the following HTTP verbs for my models: GET , POST and PUT , which means that for each resource (model class) I can insert/update/retrieve data from the following URLs: /api/myResourceName /api/myResourceName/{id} And for my sub-resources (the children models) I can do the same through the following URLs: /api/myResourceName/{id}/subresource /api/myResourceName/{id}/subresource/{subresourceId} However, in order to have a sub-resource, I necessarily need to have an IEnumerable<MySubresourceModel> in the ResourceModel , but there are many cases

How to access User in a service context in web API?

牧云@^-^@ 提交于 2019-12-04 17:20:39
问题 If you are in a controller context, you can access the current authenticated User. Take an article such as Get the current user, within an ApiController action, without passing the userID as a parameter . However, if my controller calls a service (same assembly), but here I don't have the controller context. What is the best way to actually get the authenticated user? 回答1: You can create an intermediate service to provide that functionality public interface IPrincipalProvider { IPrincipal

Unit test WebApi2 passing header values

醉酒当歌 提交于 2019-12-04 17:01:50
I am working on a project using WebApi2. With my test project I am using Moq and XUnit. So far testing an api has been pretty straight forward to do a GET like [Fact()] public void GetCustomer() { var id = 2; _customerMock.Setup(c => c.FindSingle(id)) .Returns(FakeCustomers() .Single(cust => cust.Id == id)); var result = new CustomersController(_customerMock.Object).Get(id); var negotiatedResult = result as OkContentActionResult<Customer>; Assert.NotNull(negotiatedResult); Assert.IsType<OkNegotiatedContentResult<Customer>>(negotiatedResult); Assert.Equal(negotiatedResult.Content.Id,id); } Now

OWIN OAuth 2.0 - Bearer Token Never Expire

≡放荡痞女 提交于 2019-12-04 16:55:45
I'm using the following OAuth provider and options: UserManagerFactory = () => new UserManager<IdentityUser>(new UserStore<IdentityUser>(new ApplicationDbContext())); OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory), AuthorizeEndpointPath = new PathString("/api/AccountOwin/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(2), AllowInsecureHttp = true }; app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseExternalSignInCookie