asp.net-coreasp.net-core-viewcomponentfileresult

How return a yaml file as result of an asp.net core ViewComponent


I want to create an asp.net core ViewComponent that dynamically return a yaml file based on some criteria: For example

namespace MyNameSpace {

[ViewComponent(Name = nameof(MyViewComponent))]
public class MyViewComponent : ViewComponent
{
    
    public async Task<IViewComponentResult> InvokeAsync(object input)
    {
        string yamlDocument = GetYamlDocumentByInput(input);
        //how to proceed here so that my yamlDocument is returned with the right content type?
        return View(..., yamlDocument);
    }
}}

Solution

  • you could search the view component class,and there‘s no method can return a file as result. ViewComponent

    you'd better add an action in your controller to download file,and you could send a request to this action after your view has been rendered mannully or automaticlly. and there's the codes in the action:

    public FileResult DownLoad(Person  person)
           
            {
                
                var serializer = new SerializerBuilder()
                                        .WithNamingConvention(CamelCaseNamingConvention.Instance)
                                        .Build();
                var yaml = serializer.Serialize(person);            
                byte[] yamlArray = System.Text.Encoding.UTF8.GetBytes(yaml);
                return File(yamlArray, "application/x-yml");
             }
    

    Result: Result