public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return(sample); }
/// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); }
/// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); }
/// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable <string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return(sample); } return(null); }
public async Task <Response> Handle(Request request, CancellationToken cancellationToken) { var httpContext = _httpContextAccessor.HttpContext; var defaultFormOptions = new FormOptions(); var digitalAssets = new List <DigitalAsset>(); if (!MultipartRequestHelper.IsMultipartContentType(httpContext.Request.ContentType)) { throw new Exception($"Expected a multipart request, but got {httpContext.Request.ContentType}"); } var mediaTypeHeaderValue = MediaTypeHeaderValue.Parse(httpContext.Request.ContentType); var boundary = MultipartRequestHelper.GetBoundary( mediaTypeHeaderValue, defaultFormOptions.MultipartBoundaryLengthLimit); var reader = new MultipartReader(boundary, httpContext.Request.Body); var section = await reader.ReadNextSectionAsync(); while (section != null) { DigitalAsset digitalAsset = default; var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out ContentDispositionHeaderValue contentDisposition); if (hasContentDispositionHeader) { if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition)) { using (var targetStream = new MemoryStream()) { await section.Body.CopyToAsync(targetStream); var name = $"{contentDisposition.FileName}".Trim(new char[] { '"' }).Replace("&", "and"); var bytes = StreamHelper.ReadToEnd(targetStream); var contentType = section.ContentType; digitalAsset = _context.DigitalAssets.SingleOrDefault(x => x.Name == name); if (digitalAsset == null) { digitalAsset = new DigitalAsset(name, bytes, contentType); _context.DigitalAssets.Add(digitalAsset); } else { digitalAsset.Update(bytes, contentType); } } } } digitalAssets.Add(digitalAsset); section = await reader.ReadNextSectionAsync(); } await _context.SaveChangesAsync(cancellationToken); return(new () { DigitalAssetIds = digitalAssets.Select(x => x.DigitalAssetId).ToList() }); }
/// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //Connection to database var connectionString = _configuration["MySqlConnection:MySqlConnectionString"]; services.AddDbContext <MySQLContext>(options => options.UseMySql(connectionString)); //Adding Migrations Support if (_environment.IsDevelopment()) { try { var evolveConnection = new MySql.Data.MySqlClient.MySqlConnection(connectionString); var evolve = new Evolve.Evolve("evolve.json", evolveConnection, msg => _logger.LogInformation(msg)) { Locations = new List <string> { "db/migrations" }, IsEraseDisabled = true, }; evolve.Migrate(); } catch (Exception ex) { _logger.LogCritical("Database migration failed.", ex); throw; } } //Content negociation - Support to XML and JSON services.AddMvc(options => { options.RespectBrowserAcceptHeader = true; options.FormatterMappings.SetMediaTypeMappingForFormat("xml", MediaTypeHeaderValue.Parse("text/xml")); options.FormatterMappings.SetMediaTypeMappingForFormat("json", MediaTypeHeaderValue.Parse("application/json")); }) .AddXmlSerializerFormatters(); //HATEOAS filter definitions var filterOptions = new HyperMediaFilterOptions(); filterOptions.ObjectContentResponseEnricherList.Add(new BookEnricher()); filterOptions.ObjectContentResponseEnricherList.Add(new PersonEnricher()); //Service inject services.AddSingleton(filterOptions); //Versioning services.AddApiVersioning(option => option.ReportApiVersions = true); //Add Swagger Service services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "RESTful API With ASP.NET Core 2.0", Version = "v1" }); }); //Dependency Injection services.AddScoped <IPersonBusiness, PersonBusinessImpl>(); services.AddScoped <IBookBusiness, BookBusinessImpl>(); // Não precisamos mais fazer dessa forma //services.AddScoped<IPersonRepository, PersonRepositoryImpl>(); //Dependency Injection of GenericRepository services.AddScoped(typeof(IRepository <>), typeof(GenericRepository <>)); }
/// <summary> /// Find spelling corrections /// </summary> /// Find spelling correction suggestions and return result as JSON /// <param name='value'> /// Input string /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <CorrectJsonOKResponse> > CorrectJsonWithHttpMessagesAsync(string value, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (value == null) { throw new ValidationException(ValidationRules.CannotBeNull, "value"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("value", value); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CorrectJson", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "nlp/spellcheck/correct/word/json").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (value != null) { _requestContent = SafeJsonConvert.SerializeObject(value, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <CorrectJsonOKResponse>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <CorrectJsonOKResponse>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public async Task <IActionResult> AddProductMedia() { if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType)) { ModelState.AddModelError("File", $"The request couldn't be processed (Error 1)."); // Log error return(BadRequest(ModelState)); } var boundary = MultipartRequestHelper.GetBoundary( MediaTypeHeaderValue.Parse(Request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit); var reader = new MultipartReader(boundary, HttpContext.Request.Body); var section = await reader.ReadNextSectionAsync(); while (section != null) { var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse( section.ContentDisposition, out var contentDisposition); if (hasContentDispositionHeader) { // This check assumes that there's a file // present without form data. If form data // is present, this method immediately fails // and returns the model error. if (!MultipartRequestHelper .HasFileContentDisposition(contentDisposition)) { ModelState.AddModelError("File", $"The request couldn't be processed (Error 2)."); // Log error return(BadRequest(ModelState)); } else { // Don't trust the file name sent by the client. To display // the file name, HTML-encode the value. var trustedFileNameForDisplay = WebUtility.HtmlEncode( contentDisposition.FileName.Value); var trustedFileNameForFileStorage = Path.GetRandomFileName(); // **WARNING!** // In the following example, the file is saved without // scanning the file's contents. In most production // scenarios, an anti-virus/anti-malware scanner API // is used on the file before making the file available // for download or for use by other systems. // For more information, see the topic that accompanies // this sample. var streamedFileContent = await FileHelpers.ProcessStreamedFile( section, contentDisposition, ModelState, _permittedExtensions, _fileSizeLimit); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } using (var targetStream = System.IO.File.Create( Path.Combine(_targetFilePath, trustedFileNameForFileStorage))) { await targetStream.WriteAsync(streamedFileContent); _logger.LogInformation( "Uploaded file '{TrustedFileNameForDisplay}' saved to " + "'{TargetFilePath}' as {TrustedFileNameForFileStorage}", trustedFileNameForDisplay, _targetFilePath, trustedFileNameForFileStorage); } } } // Drain any remaining section body that hasn't been consumed and // read the headers for the next section. section = await reader.ReadNextSectionAsync(); } return(Ok()); }
public ShouldHaveApiContentType(string contentType) : this(MediaTypeHeaderValue.Parse(contentType)) { }
public ShouldHaveApiContentType(MediaTypeHeaderValue contentType) => this.contentType = contentType;
private GingerHttpRequestMessage GetRequest(NodePlatformAction platformAction) { GingerHttpRequestMessage Request = new GingerHttpRequestMessage(); Request.URL = new Uri(platformAction.InputParams["EndPointURL"].ToString()); if (platformAction.ActionType == "ActWebAPISoap") { Request.Method = "POST"; Request.ContentType = "XML"; } else { Request.Method = platformAction.InputParams["RequestType"].ToString(); Request.ContentType = platformAction.InputParams.ContainsKey("ContentType") ? platformAction.InputParams["ContentType"].ToString() : ""; if (platformAction.InputParams["RequestKeyValues"] is Newtonsoft.Json.Linq.JArray RObj) { Request.RequestKeyValues = new List <RestAPIKeyBodyValues>(); foreach (Newtonsoft.Json.Linq.JToken Jt in RObj.Children()) { RestAPIKeyBodyValues RKV = new RestAPIKeyBodyValues(); if (Jt["ValueType"].ToString() == "1") { RKV.ValueType = RestAPIKeyBodyValues.eValueType.File; Byte[] FileBytes = (Byte[])Jt["FileBytes"]; string Path = Jt["Value"].ToString(); RKV.Filename = System.IO.Path.GetFileName(Path); ByteArrayContent fileContent = new ByteArrayContent(FileBytes); fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); RKV.Content = fileContent; } RKV.Value = Jt["Value"].ToString(); RKV.Param = Jt["Param"].ToString(); Request.RequestKeyValues.Add(RKV); } } } Request.BodyString = platformAction.InputParams.ContainsKey("RequestBody") ? platformAction.InputParams["RequestBody"].ToString() : ""; if (platformAction.InputParams["Headers"] is Newtonsoft.Json.Linq.JObject JsonObj) { foreach (Newtonsoft.Json.Linq.JProperty Jt in JsonObj.Children()) { Request.Headers.Add(new KeyValuePair <string, string>(Jt.Name, Jt.Value.ToString())); } } return(Request); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var connectionString = _configuration["MySqlConnection:MySqlConnectionString"]; services.AddDbContext <MySQLContext>(options => options.UseMySql(connectionString)); //Adding Migrations Support ExecuteMigrations(connectionString); var signingConfigurations = new SigningConfigurations(); services.AddSingleton(signingConfigurations); var tokenConfigurations = new TokenConfigurations(); new ConfigureFromConfigurationOptions <TokenConfigurations>( _configuration.GetSection("TokenConfigurations") ) .Configure(tokenConfigurations); services.AddSingleton(tokenConfigurations); services.AddAuthentication(authOptions => { authOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; authOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(bearerOptions => { var paramsValidation = bearerOptions.TokenValidationParameters; paramsValidation.IssuerSigningKey = signingConfigurations.Key; paramsValidation.ValidAudience = tokenConfigurations.Audience; paramsValidation.ValidIssuer = tokenConfigurations.Issuer; // Validates the signing of a received token paramsValidation.ValidateIssuerSigningKey = true; // Checks if a received token is still valid paramsValidation.ValidateLifetime = true; // Tolerance time for the expiration of a token (used in case // of time synchronization problems between different // computers involved in the communication process) paramsValidation.ClockSkew = TimeSpan.Zero; }); // Enables the use of the token as a means of // authorizing access to this project's resources services.AddAuthorization(auth => { auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireAuthenticatedUser().Build()); }); services.AddMvc(options => { options.RespectBrowserAcceptHeader = true; options.FormatterMappings.SetMediaTypeMappingForFormat("xml", MediaTypeHeaderValue.Parse("text/xml")); options.FormatterMappings.SetMediaTypeMappingForFormat("json", MediaTypeHeaderValue.Parse("application/json")); }) .AddXmlDataContractSerializerFormatters() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); var filterOptions = new HyperMediaFilterOptions(); filterOptions.ObjectContentResponseEnricherList.Add(new PersonEnricher()); services.AddSingleton(filterOptions); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "RESTFULL API with ASP.NET Core 2.0", Version = "v1" }); }); //Dependency Injection services.AddScoped <IPersonBusiness, PersonBusinessImpl>(); services.AddScoped <IBookBusiness, BookBusinessImpl>(); services.AddScoped <IUserBusiness, UserBusinessImpl>(); services.AddScoped <IUserRepository, UserRepositoryImpl>(); services.AddScoped <IPersonRepository, PersonRepositoryImpl>(); services.AddScoped <IFileBusiness, FileBusinessImpl>(); //Dependency Injection of GenericReository services.AddScoped(typeof(IRepository <>), typeof(GenericRepository <>)); }