in my IIS local and hosted in aws got this error when I publish my web API app got this error
asp.net
in my IIS local and hosted in aws got this error when I publish my web API app got this error
asp.net
When I execute the following code to get the token, I got the error "SocketException: No connection could be made because the target machine actively refused (ipaddress)". What caused the error? Did I miss something? Thanks.
using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:1234"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); var body = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("grant_type", "password"), new KeyValuePair<string, string>("client_id", "client_id"), new KeyValuePair<string, string>("client_screte", "client_screte"), new KeyValuePair<string, string>("username", "xyz"), new KeyValuePair<string, string>("password", "Password"), new KeyValuePair<string, string>("scope", "scope"), }; var content = new FormUrlEncodedContent(body); HttpResponseMessage tokenResponse = await client.PostAsync("/connect/token", content); }
Hello,
I have created custom authorization attribute with claim based.
[RoutePrefix("api/Orders")] public class OrdersController : ApiController { [CustomAuthorizeAPI(ClaimType = "module", ClaimValue = "Order-view")] [Route("")] public IHttpActionResult Get() { return Ok(Order.CreateOrders()); } }
public class CustomAuthorizeAPI : AuthorizationFilterAttribute { public string ClaimType { get; set; } public string ClaimValue { get; set; } public override Task OnAuthorizationAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken) { var principal = actionContext.RequestContext.Principal as ClaimsPrincipal; if (principal==null || !principal.Identity.IsAuthenticated) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); return Task.FromResult<object>(null); } if (!(principal.HasClaim(x => x.Type == ClaimType && x.Value == ClaimValue))) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); return Task.FromResult<object>(null); } //User is Authorized, complete execution return Task.FromResult<object>(null); } }
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
but HttpStatusCode.Unauthorized respone not created instead it created Not Found 404
but when i use HttpStatusCode.NotAcceptable,HttpStatusCode.BadRequest,HttpStatusCode.InternalServerError, HttpStatusCode.InternalServerError etc... all are working fine.
Only HttpStatusCode.Unauthorized giving 404.
Did i make any mistake?
Appricate quick and best response.
I can't seem to get my service to return XML. I keep getting a 406 error. It seems so simple and all of the articles I've read make it look easy. For me, however, it simply does not work. What am I missing?
Using MVC CORE 2,0
I've got this in startup.cs
services.AddMvc(options =>
{
options.RespectBrowserAcceptHeader = true;
options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
options.FormatterMappings.SetMediaTypeMappingForFormat("xml", MediaTypeHeaderValue.Parse("application/xml"));
});
I've got this on my controller:
[HttpGet]
[FormatFilter]
[Route("api/[controller]/{agencyId}.{format?}")]
public async Task<IActionResult> Get(string agencyId)
In Postman, I specify "Accept" to "application/xml"
I call my service with /api/agent/1234, it works and returns JSON. When I do /api/agent/1234.xml, I get the 406.
It seems I'm doing everything correctly. What's wrong? Thanks
//PUT:api/GetUsers/id [HttpPut] public void EditUser (int id, User user) { if (!ModelState.IsValid) { throw new HttpResponseException(HttpStatusCode.BadRequest); } else { var userInDb = db.Users.SingleOrDefault(e => e.Id == id); if(userInDb == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } else { userInDb.Name = user.Name; userInDb.Email = user.Email; userInDb.Password = user.Password; userInDb.ConfirmPassword = user.ConfirmPassword; userInDb.Birthdate = user.Birthdate; userInDb.mobileNo = user.mobileNo; userInDb.upImage = user.upImage; userInDb.Height = user.Height; userInDb.Weight = user.Weight; userInDb.GenderId = user.GenderId; userInDb.BloodTypeId = user.BloodTypeId; userInDb.DiseaseId = user.DiseaseId; userInDb.EventId = user.EventId; db.SaveChanges(); } } }
I have an Address class with the standard Address1, Address2, City, State, Zip5, Zip4 properties. I also have property with a getter only that combines the city/state/zip. It looks like this:
[XmlElement("cityStateZip")]
public string CityStateZip
{
get { return $"{this.City}, {this.State} {this.Zip5}" + ((this.Zip4==null) ? "" : $"-{this.Zip4}"); }
}
When I call my service, the address is returned with the all elements in the xml, except for this one. I can see, when debugging, the property is combining the values correctly, but it's simply missing from the resultant xml.
Why?
Hello
How are you today?
I am going to develop WEB API by using bearer token.
My question is this:
I send my login details to web API from client side, and then web API send token to client.
It's expiration time is 1 day.
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
But even if I restart web API server IIS, but client still can access web API via old token.
It means token is not stored in server side?
Thank you
Best Regards
Whenever I’m running a DeserializeObject command to convert JSON to C# object, I’m getting the JsonReaderException, and the process stops at this line in my JSON:
\"emails\": [account%40mydomain.com],\n\t\
(which equals to "emails": "[account@mydomain.com]")
I’m doing the actual deserialization by using these lines of code:
var body = actionContext.Request.Content.ReadAsStringAsync().Result;
var chRequest = JsonConvert.DeserializeObject<MyObject>(body);
All the other fields (almost 20 of them) in the JSON message gets deserialized without issues. The process fails on the lines where I process arrays (there is another array in the JSON message, which fails with the same message).
In MyObject, Emails property looks like this:
[JsonProperty("emails")]
public string Emails { get; set; }
The data is coming from an external system by using POST method. It is sent asapplication/x-www-form-urlencoded.
After trying to figure this out this issue for days, I’d really like to get some fresh ideas on how to solve this.
Hello
How are you today?
I have a Web API project which using token based authentication.
I already make some claims for user authorization.
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var identity = new ClaimsIdentity(context.Options.AuthenticationType); string reportLevel = //Get Report level from DB. identity.AddClaim(new Claim("reportlevel", reportLevel.ToString()));
context.Validated(identity); }
So I have claim which named reportlevel.
But problem is this:
This report level is changed dynamically.
So if this report level changed, I need to update claim.
So I did this:
public static void AddUpdateClaim(this IPrincipal currentPrincipal, string key, string value) { var identity = currentPrincipal.Identity as ClaimsIdentity; if (identity == null) return; // check for existing claim and remove it var existingClaim = identity.FindFirst(key); if (existingClaim != null) identity.RemoveClaim(existingClaim); // add new claim identity.AddClaim(new Claim(key, value)); var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identity), new AuthenticationProperties() { IsPersistent = true }); }
////Below is test controller public class TestController: ApiController { [HttpGet] public HttpResponseMessage UpdateClaim(string reportlevel) { ClaimsIdentity claimsIdentity = User.Identity as ClaimsIdentity; AddUpdateClaim(User, "reportlevel", reportlevel.ToString());
return HttpRequest.CreateResponse(HTTPSTATUSCODE.OK, "update success"); } [HttpGet] public HttpResponseMessage GetClaim() { ClaimsIdentity claimsIdentity = User.Identity as ClaimsIdentity; string reportlevel = claimsIdentity.FindFirst("reportlevel").Value;
return HttpRequest.CreateResponse<string>(HTTPSTATUSCODE.OK, reportlevel); } }
But even I update reportlevel claim in UpdateCliam() , but when I get reportlevel from GetCliam(), it is not updated.
What is the problem ?
Thank you
Best Regards
hello ,
I want to create stream API for .mp3 track. so that i can use(soundmanger2 player with stream)
found that sound cloud does("https://api.soundcloud.com/tracks/173676777/stream")
is there any difference between download track using stream and play track using stream?
because i'm already using stream method to download track with the help of articale http://piotrwalat.net/file-download-service-with-resume-support-using-asp-net-web-api/
here is my download code:
public HttpResponseMessage Head(string fileName) { if (!FileProvider.Exists(fileName)) { //if file does not exist return 404 throw new HttpResponseException(HttpStatusCode.NotFound); } long fileLength = FileProvider.GetLength(fileName); ContentInfo contentInfo = GetContentInfoFromRequest(this.Request, fileLength); var response = new HttpResponseMessage(); response.Content = new ByteArrayContent(new byte[0]); SetResponseHeaders(response, contentInfo, fileLength, fileName); return response; } [HttpGet] [Route("download/{trackId:int}")] public async Task<HttpResponseMessage> download(int trackId) { Track t = new Track(trackId); if (t == null || !FileProvider.Exists(t.DownloadUrl)) { //if file does not exist return 404 throw new HttpResponseException(HttpStatusCode.NotFound); } string fileName = t.DownloadUrl; long fileLength = FileProvider.GetLength(fileName); ContentInfo contentInfo = GetContentInfoFromRequest(this.Request, fileLength); var stream = new PartialReadFileStream(FileProvider.Open(fileName), contentInfo.From, contentInfo.To); var response = new HttpResponseMessage(); response.Content = new StreamContent(stream); SetResponseHeaders(response, contentInfo, fileLength, t.Title); return response; } private ContentInfo GetContentInfoFromRequest(HttpRequestMessage request, long entityLength) { var result = new ContentInfo { From = 0, To = entityLength - 1, IsPartial = false, Length = entityLength }; RangeHeaderValue rangeHeader = request.Headers.Range; if (rangeHeader != null && rangeHeader.Ranges.Count != 0) { //we support only one range if (rangeHeader.Ranges.Count > 1) { //we probably return other status code here throw new HttpResponseException(HttpStatusCode.RequestedRangeNotSatisfiable); } RangeItemHeaderValue range = rangeHeader.Ranges.First(); if (range.From.HasValue && range.From < 0 || range.To.HasValue && range.To > entityLength - 1) { throw new HttpResponseException(HttpStatusCode.RequestedRangeNotSatisfiable); } result.From = range.From ?? 0; result.To = range.To ?? entityLength - 1; result.IsPartial = true; result.Length = entityLength; if (range.From.HasValue && range.To.HasValue) { result.Length = range.To.Value - range.From.Value + 1; } else if (range.From.HasValue) { result.Length = entityLength - range.From.Value + 1; } else if (range.To.HasValue) { result.Length = range.To.Value + 1; } } return result; } private void SetResponseHeaders(HttpResponseMessage response, ContentInfo contentInfo, long fileLength, string fileName) { response.Headers.AcceptRanges.Add("bytes"); response.StatusCode = contentInfo.IsPartial ? HttpStatusCode.PartialContent : HttpStatusCode.OK; response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName = fileName; response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); response.Content.Headers.ContentLength = contentInfo.Length; if (contentInfo.IsPartial) { response.Content.Headers.ContentRange = new ContentRangeHeaderValue(contentInfo.From, contentInfo.To, fileLength); } }
i try to use same code/url for play stream. it is working but, when i try to seek/move tack backward/forward then i'm getting connection reset issues on networkconsole(net::ERR_CONNECTION_RESET
angular-soundmanager2.js:937 95239018: progress, 97% loaded)
Please suggest and advice me, and any best way to create audio api for play using stream.
Appriceated for quick and best respone
CORS is browser issue and browser prevent send request to different domain. suppose i have developed one web service project and one mvc project. the jquery in mvc project will call action in web service project but for that we need to enable cors at web service project....why?
public static class WebApiConfig { public static void Register(HttpConfiguration config) { // New code config.EnableCors(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } [EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")] public class ItemsController : ApiController { public HttpResponseMessage GetAll() { ... } public HttpResponseMessage GetItem(int id) { ... } public HttpResponseMessage Post() { ... } [DisableCors] public HttpResponseMessage PutItem(int id) { ... } }
browser prevent jquery code to call cross domain but we are enabling things at web service project. why not we enable cors at client application which is making cross domain request from browser?
suppose jquery call this http://mywebservice/api/test but get error when enable cors then works. how jquery understand cors is enabled ?
when we enable cors at web service level then two round trip occur?
first jquery send request to web service and web service send response to browser saying yes that domain can access me and then browser again send the same request to web service. actually what happen not very clear.
i read a article already but was not very details. please some one tell me how browser prevent cors and how many round trip occur for cors ?
<script> // TODO: Replace with the URL of your WebService app var serviceUrl = 'http://mywebservice/api/test'; function sendRequest() { var method = $('#method').val();$.ajax({ type: method, url: serviceUrl }).done(function (data) {$('#value1').text(data); }).error(function (jqXHR, textStatus, errorThrown) {$('#value1').text(jqXHR.responseText || textStatus); }); }</script>
If you watch the HTTP traffic in a tool like Fiddler, you will see that the browser does send the GET request,
and the request succeeds, but the AJAX call returns an error. It's important to understand that same-origin policy
does not prevent the browser from sending the request. Instead, it prevents the application from seeing the response.
people always said cors is browser issue but from the above text it seems cors is not browser issue rather it is upto web service which prevent cross domain call.....am i right?
CORS is REST specific things only because for ASMX web service jquery i guess can call it whether web service in same domain or different one.
share the knowledge.
Hello,
I'm trying to figure out how to create a url to manually test an API. I'm talking about a string of characters that I can enter into my browsers address bar and when I press enter, it processes the string.
I'm working with the company whose API information is here.
If my key is "xyz" and if I use a string like: "https://secure.chinavasion.com/api/getProductList.php?key=xyz&categories="Cell Phone Watch" in the address bar, I get thiserror.
Does anybody know how to compose a url string to test this manually?
Thanks,
Tony
Hi guys!
I'm trying to upload image from client to server.
The image in base64 string works in client side, because it is displayed correctly into an image viewer.
Then, when I try to upload the image the file created is corrupted, and I can't open it. It seems that I'm loosing some part of base64 string passing it from client side to server side.
Server side code:
[Produces("application/json")] [Route("api/pubblicazioni")] public class PubblicazioniController : Controller { [Route("crea")] [HttpPost] public IActionResult CreaPubblicazione(Int32 idutente, String testo, String immagine) { if (Pubblicazione.CreaPubblicazione(idutente, testo, immagine) == true) { return Ok(); } else { return Unauthorized(); } } } public static bool CreaPubblicazione(Int32 idutente, String testo, String immagine) { var bytes = Convert.FromBase64String(immagine); String nomefile = idpubblicazione.ToString() + ".jpg"; File.WriteAllBytes(path + nomefile, bytes); return true; } catch (Exception ex) { return false; } } }
Here it is my client side code:
Pubblica(idutente: any, testo: any, immagine: any) { var headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); let options = new RequestOptions({ headers: headers }); let params = new URLSearchParams() params.set('idutente', idutente); params.set('testo', testo); params.set('immagine', immagine); return new Promise((resolve, reject) => { this.http.post(this.conn.connessione+"/api/pubblicazioni/crea", params.toString(), options) .subscribe( data => { resolve(data); }, error => { reject(error); } ); });
const options: CameraOptions = { quality: 100, destinationType: this.camera.DestinationType.FILE_URI, encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE, sourceType:sourceType }
}
here a sample code added for basic auth
public class BasicAuthenticationAttribute : AuthorizationFilterAttribute { public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext) { if (actionContext.Request.Headers.Authorization == null) { actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); } else { // Gets header parameters string authenticationString = actionContext.Request.Headers.Authorization.Parameter; string originalString = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationString)); // Gets username and password string usrename = originalString.Split(':')[0]; string password = originalString.Split(':')[1]; // Validate username and password if (!ApiSecurity.VaidateUser(usrename, password)) { // returns unauthorized error actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); } } base.OnAuthorization(actionContext); } } [BasicAuthentication] public class BlogController : ApiController { // Add your action here } $.ajax({ url: 'http://localhost:1312/api/Blog?type=json', type: "POST", contentType: "application/json", data: JSON.stringify(blogData), dataType: "json", headers: { 'Authorization' :'Basic ' + btoa(username + ':' + password) }, success: function (result) { // On success, 'data' contains a list of products. var htmlContent = ""; $("#blogs > tbody > tr").remove(); $.each(result, function (key, item) { htmlContent = htmlContent + "<tr><td>" + item.Id + "</td><td>" + item.Name + "</td><td>" + item.Url + "</td></tr>"; }); // Appending HTML content $('#blogs').append(htmlContent); }, error: function (err) { alert(err.statusText); } });
see the how header data passed from client side to server side headers: { 'Authorization' :'Basic ' + btoa(username + ':' + password) },
it is mandatory that we need to mention Authorization and Basic the word in header or is it a convention only which we may not use when we call action with jquery for basic auth?
i also see this url https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/basic-authentication
response.Headers.Add("WWW-Authenticate",string.Format("Basic realm=\"{0}\"", Realm));
what is the meaning of the word WWW-Authenticate & Basic realm
thanks
i found the code from https://forums.asp.net/t/2104737.aspx?Getting+Owin+Authorization+token+with+AJAX
https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/individual-accounts-in-web-api
var loginData = { grant_type: 'password', username: self.loginEmail(), password: self.loginPassword() };$.ajax({ type: 'POST', url: '/Token', headers: { "Accept": "application/json" }, contentType: "application/x-www-form-url; charset=urf-8", data: loginData }).done(function (data) { self.user(data.userName); // Cache the access token in session storage. sessionStorage.setItem(tokenKey, data.access_token); }).fail(showError);
1) what is the meaning of grant_type: 'password' ?
2) is it mandatory to mention when passing data to server in case of token auth?
3) is it mandatory to mention the same in case of jwt token auth?
4) what is the meaning of headers: { "Accept": "application/json" }, ?
5) what is the meaning of contentType: "application/x-www-form-url; charset=urf-8",
please discuss my 5 points. thanks
Origins
Here, we need to set Origins which means from which domain the requests will accept. If you have more than one domain, then you can set as comma separated. Additionally if you want any domain request to be accepted then use wild card as "*"
suppose when i need to enable CORS for multiple external domain then we need to use comma as separator for multiple domain like
[EnableCors(origins: "http://localhost:5901/DemoApp/WebForm1.aspx,
http://mudomain1:5901/DemoApp/WebForm1.aspx", headers: "*", methods: "*")] public class ValuesController : ApiController { }
1) suppose when we like to save external domain path in db then how could i mention multiple domain path from db to EnableCors attribute?
2) see the below code
[EnableCors(origins: "*", headers: "*", methods: "*", exposedHeaders: "X-My-Header")] public class TestController : ApiController { }
what is the meaning of EnableCors(origins: "*") does it means web api allow any domain to call its action ?
thanks
I write a wcf service(.net framework 4.6.1) by Visual Studio 2017 community. I want to return a json string in the function GetUserTable. So I add the UriTemplate to pass the userID.
But I use the weburl as below:
http://localhost/WcfServiceAKS461/Service1.svc/data/1
Does somebody know how to solve this route problem?
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "data/{userID}")] public UserTable GetUserTable(string userID) { using (DatabaseAKStudioEntities context = new DatabaseAKStudioEntities()) { var usertable = context.UserTables.First(a => a.UserID == userID); //var json = new JavaScriptSerializer().Serialize(usertable); return usertable; } }
I always get {} string of yourJson. I had the line
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
into Application_Start function, but I still get {} json string from api/values/3
Does somebody know how to solve this problem?
public class Person { string FirstName { get; set; } string LastName { get; set; } public Person(string fn, string ln) { FirstName = fn; LastName = ln; } }
public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); } }
// GET api/values/3 public string Get(int id) { //var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; //json.SerializerSettings.DateFormatHandling //= Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat; Person p = new Person("John", "Min"); string yourJson = Newtonsoft.Json.JsonConvert.SerializeObject(p); //var response = this.Request.CreateResponse(HttpStatusCode.OK); //response.Content = new StringContent(yourJson, Encoding.UTF8, "application/json"); return yourJson; }
see the code
var loginData ={ grant_type:'password', username:self.loginEmail(), password:self.loginPassword()};$.ajax({ type:'POST', url:'/Token', headers:{"Accept":"application/json"}, contentType:"application/x-www-form-url; charset=urf-8", data: loginData}).done(function(data){self.user(data.userName);// Cache the access token in session storage. sessionStorage.setItem(tokenKey, data.access_token);}).fail(showError);
is it mandatory that we need to include Accept and Content-Type attribute with jquery when calling web api action?
when we set json media type like in web api
public static void Register(HttpConfiguration config) { config.Formatters.Clear(); config.Formatters.Add(new JsonMediaTypeFormatter()); }); }
then also is it mandatory to mention Accept and Content-Type attribute in jquery?
some time i also saw people use dataTypewhen calling web api by jquery. when we need to say data type ?
see a example of jquery code which use dataTypein jquery when calling web api.
$.ajax({ url: 'http://localhost:11129/api/values', type: 'GET', dataType: 'xml', ContentType: "application/rss+xml", success: function(data, textStatus, xhr) { console.log(data); }, error: function(xhr, textStatus, errorThrown) { console.log('a' + textStatus); } }).done(function() {});
i read few write up on content negotiation
http://www.tutorialsteacher.com/webapi/request-response-data-formats-in-web-api
https://msdn.microsoft.com/en-us/magazine/dn574797.aspx
https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/content-negotiation
https://dejanstojanovic.net/aspnet/2014/may/forcing-accept-type-for-webapi-call/
http://binaryintellect.net/articles/6ef2100b-6561-4997-9df5-0864c5f23a21.aspx
https://weblog.west-wind.com/posts/2012/Aug/21/An-Introductio
i am using VS2013 to develop web api project. i need to know when we select web api template then we got some code but tell me what to add there to get access token?
when web api generate access token does it save in db as result it can check later to find the token was generated by system or not for validation purpose?
what code i need to add in project to get refresh token. suppose when my token will expire then i have to check if the token found in db then i will return refresh token to client.
please share the instruction to work with token auth with default web api template.....i am working with vs2013 ide. thanks